package com.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.filechooser.FileFilter;

import com.util.Design;
import com.util.Shelf;
import com.util.Workspace;
import com.tool.ExtensionFileFilter;
import com.tool.ShelfTableModel;

public class MainFrame extends JFrame {
	static MainFrame frame;
	Workspace w = null;

	String password;
	String username;

	JTabbedPane jtp;
	JTable table;
	ShelfTableModel stm;
	
	JPanel loginPanel;
	JLabel userLabel;
	JLabel passLabel;
	JLabel status;
	JTextField userText;
	JPasswordField passText;
	JButton submit;

	JPanel workspacePanel;
	JLabel designLabel;
	JComboBox designCombo;
	JButton add;
	JButton remove;
	JButton edit;

	JPanel wdPanel;
	JPanel shelfPanel;
	JTextField begField;
	JTextField endField;

	public MainFrame(String string) {
		super(string);

		jtp = new JTabbedPane();
		status = new JLabel();

		loginPanel = new JPanel();
		userLabel = new JLabel("Username: ");
		passLabel = new JLabel("Password: ");

		userText = new JTextField(15);
		passText = new JPasswordField(15);

		submit = new JButton("Login");

		JPanel p1 = new JPanel();
		p1.setLayout(new BorderLayout());

		p1.add(loginPanel, BorderLayout.NORTH);
		loginPanel.setLayout(new GridLayout(3, 3));
		loginPanel.add(userLabel);
		loginPanel.add(userText);
		loginPanel.add(passLabel);
		loginPanel.add(passText);
		loginPanel.add(new Box(1));
		loginPanel.add(submit);
		loginPanel.setSize(300, 300);

		submit.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if (w == null) {
					w = new Workspace(userText.getText(), new String(passText.getPassword()));
					if (w.isConnected()) {
						jtp.addTab("Workspace", workspacePanel);

						if (w.getDesigns().keySet() != null)
							for (String name : w.getDesigns().keySet()) {
								designCombo.addItem(name);
							}
						jtp.setSelectedIndex(1);
						status("Logged In");
					} else {
						status("Invalid username/password");
						w = null;
					}
				} else {
					status("Already logged in");
				}
			}
		});

		workspacePanel = new JPanel();
		designLabel = new JLabel("Select Design: ");
		designCombo = new JComboBox();
		
		//add design
		add = new JButton("Add");
		
		//delete selected design design
		remove = new JButton("Delete");
		
		
		edit = new JButton("Update");

		workspacePanel.add(designLabel);
		workspacePanel.add(designCombo);
		workspacePanel.add(add);
		
		add.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser chooser = new JFileChooser();
				//File Filter
				FileFilter filter1 = new ExtensionFileFilter("Images", new String[] { "JPG", "JPEG", "PNG", "GIF"});
			    chooser.addChoosableFileFilter(filter1);
			    chooser.setAcceptAllFileFilterUsed(false);

				int returnVal = chooser.showOpenDialog(workspacePanel);
				
				if (returnVal == JFileChooser.APPROVE_OPTION) {
					// Get file from user, and store it to a buffered img, which
					// is then uploaded to DB.
					File libraryMap = chooser.getSelectedFile();
					BufferedImage img = null;
					try {
						img = ImageIO.read(libraryMap);
					} catch (IOException e) {
						status("Error creating buffered img");
					}
					if (img != null && !w.createDesign("TEST", img)) {
						status("Error uploading to DB");	
					}else{
						status("Library created");
						designCombo.addItem("TEST");
					}
				}
				else{
					status("Must select a valid image");
				}
			}

		});
		workspacePanel.add(remove);
		remove.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				String selected = (String)designCombo.getSelectedItem();
				//check for selection
				if(selected == null || selected.equals(" "))
					status.setText("No designs");
				else{
					//ask for confirmation
					int toDelete = JOptionPane.showConfirmDialog(frame, "Are you sure you want to delete " + selected + "?", "Delete Design", JOptionPane.YES_NO_OPTION);
					//if yes and successfully deleted from storage
					if(toDelete == JOptionPane.YES_OPTION && w.deleteDesign(selected)){
						designCombo.removeItemAt(designCombo.getSelectedIndex());
					}
					else
						status("Canceled deleting " + selected);
				}
			}
		});
		workspacePanel.add(edit);
		edit.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				if(jtp.getTabCount() == 3){
					//TO DO. Save existing workspace
					jtp.remove(2);
				}
				
				String selected = (String)designCombo.getSelectedItem();
				//check for selection
				if(selected == null || selected.equals(" "))
					status.setText("No design to edit");
				else{
					w.setWorkingDesign(selected);
					jtp.add("Working Design", getWorkingDesign());
					jtp.setSelectedIndex(2);
				}	
			}

			private JPanel getWorkingDesign() {
				Design d = w.getWorkingDesign();
				
				JPanel panel = new JPanel();
			
				JLabel picLabel = new JLabel(new ImageIcon(d.getLibrary().getImg()));
				picLabel.addMouseListener(new MouseAdapter(){
					public void mouseClicked(MouseEvent e){
						  int result = JOptionPane.showConfirmDialog(null, shelfPanel, "Please Enter Beggining and Ending Shelf Ranges", JOptionPane.OK_CANCEL_OPTION);
						  if(result == JOptionPane.YES_OPTION){
							 Shelf s = new Shelf(e.getX(), e.getY(), begField.getText(), endField.getText());
							 if(w.addShelf(s)){
									 stm.addShelf(s);
									 status("Added Shelf");
							 }
							 else
								 status("Failed to add shelf");
						  }
					}
				});
						
				JPanel controlPanel = new JPanel();
				controlPanel.setLayout(new BorderLayout());
				
				stm = new ShelfTableModel(w.getWorkingDesign().getShelves());
				table = new JTable(stm);
				stm.addTableModelListener(new TableModelListener(){
					public void tableChanged(TableModelEvent e) {
				        int row = e.getFirstRow();
				        int col = e.getColumn();
				        
				        ShelfTableModel model = (ShelfTableModel)e.getSource();
  
				        
				        Shelf s = model.getRow(row);
				        if(w.updateShelf(row, s)){
				        	status("Shelf updated");
				        }
				        else{
				        	status("Shelf not updated");
				        }
				    }
				});
				
				JPanel buttonPanel = new JPanel();
				JButton remove = new JButton("Remove");
				remove.addActionListener(new ActionListener(){

					@Override
					public void actionPerformed(ActionEvent e) {
						if(w.removeShelf(table.getSelectedRow())){
							stm = new ShelfTableModel(w.getWorkingDesign().getShelves());
							table.setModel(stm);
							status("Removed Shelf");
						}	
						else
							stm = new ShelfTableModel(w.getWorkingDesign().getShelves());
							table.setModel(stm);
							status("Failed to remove shelf");
					}
					
				});
				
				buttonPanel.add(remove);
				controlPanel.add(table, BorderLayout.CENTER);
				controlPanel.add(buttonPanel, BorderLayout.EAST);
				controlPanel.setSize(WIDTH, 200);
				
				panel.setLayout(new BorderLayout());
				panel.add(new JScrollPane(picLabel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
				panel.add(controlPanel, BorderLayout.SOUTH);
				
				return panel;
			}
		});

		jtp.addTab("Log In", p1);
		
		begField = new JTextField(10);
		endField = new JTextField(10);

		shelfPanel = new JPanel();
		shelfPanel.add(new JLabel("Beginning Id:"));
		shelfPanel.add(begField);
		shelfPanel.add(Box.createHorizontalStrut(15)); // a spacer
		shelfPanel.add(new JLabel("Ending Id:"));
		shelfPanel.add(endField);
		

		this.setLayout(new BorderLayout());
		this.add(jtp, BorderLayout.CENTER);
		this.add(status, BorderLayout.SOUTH);

		this.setSize(600, 600);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}

	public static void main(String[] args) {
		frame = new MainFrame("Library Manager");
	}

	public void status(String text){
		status.setText(text);
	}
}
